package com.pussinboots.morning.sync.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pussinboots.morning.sync.dao.ProductAreaMapper;
import com.pussinboots.morning.sync.entity.Area;
import com.pussinboots.morning.sync.entity.ProductArea;
import com.pussinboots.morning.sync.service.IAreaService;
import com.pussinboots.morning.sync.service.IProductAreaService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品-区域关联表 服务实现类
 * </p>
 *
 * @author BaoZhou
 * @since 2019-09-11
 */
@Service
public class ProductAreaServiceImpl extends ServiceImpl<ProductAreaMapper, ProductArea> implements IProductAreaService {

    @Autowired
    private IAreaService areaService;

    @Override
    @Transactional
    public boolean add1ProductTo32provinceRltn(List<Long> productIds) {
        List<Area> provinceList = areaService.list(new QueryWrapper<Area>().eq("level", 1));
        if (provinceList.isEmpty()) {
            System.out.println("区域表无省份信息");
            return false;
        }

        val paList = new ArrayList<ProductArea>();
        ProductArea pa;
        for (Area area_ : provinceList) {
            for (Long productId : productIds) {
                pa = ProductArea.builder()
                        .areaCode(area_.getId())
                        .productId(productId.intValue())
                        .build();
                paList.add(pa);
            }
        }
        if (paList.isEmpty()) {
            System.out.println("组装区域商品关联信息出错");
        }

        if(!this.saveBatch(paList)){
            System.out.println("插入区域商品关联信息出错");
        }
        return true;
    }

    @Override
    @Transactional
    public boolean remove1ProductTo32provinceRltn(List<Long> productIds) {
        if (!this.remove(new QueryWrapper<ProductArea>().in("product_id", productIds))) {
            System.out.println("区域关联商品信息删除失败");
            return false;
        }
        return true;
    }

    @Override
    @Transactional
    public boolean update1ProductTo32provinceRltn(List<Long> productIds) {
        boolean result = true;
        if (!remove1ProductTo32provinceRltn(productIds)) {
            System.out.println("更新删除区域商品关联信息时，删除步骤失败");
            return false;
        }
        if (!add1ProductTo32provinceRltn(productIds)) {
            System.out.println("更新删除区域商品关联信息时，添加步骤失败");
            return false;
        }
        return true;
    }
}